/*  
 * i-OSGi - Tunable Bundle Isolation for OSGi
 * Copyright (C) 2011  Sven Schulz
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.iosgi.ie.process;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.Hashtable;

import org.osgi.framework.Bundle;

/**
 * @author Sven Schulz
 */
public class LocalBundle implements InvocationHandler {

	private static <K, V> Dictionary<K, V> copy(Dictionary<K, V> src) {
		Hashtable<K, V> copy = new Hashtable<K, V>();
		for (Enumeration<K> e = src.keys(); e.hasMoreElements();) {
			K k = e.nextElement();
			copy.put(k, src.get(k));
		}
		return copy;
	}

	private final Bundle bundle;

	LocalBundle(Bundle b) {
		this.bundle = b;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		String methodName = method.getName();
		if (methodName.equals("getHeaders")) {
			Dictionary<String, Object> headers = (Dictionary<String, Object>) method
					.invoke(bundle, args);
			return copy(headers);
		}
		return method.invoke(bundle, args);
	}

}
